package level.editor.control.main;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.TreeMap;

import javax.swing.JPanel;

import level.editor.control.layer.LayerImage;

public class Minimap extends JPanel
{

	public Minimap()
	{
		super();
		setOpaque(false);
		images = new TreeMap<Integer, LayerImage>();
	}

	public void put(Integer integer, LayerImage image)
	{
		if (images.get(integer) != null)
		{
			images.remove(integer);
		}
		images.put(integer, image);
	}

	@Override
	public void paintComponent(Graphics gOld)
	{
		setSize(getParent().getSize());
		Graphics2D g = (Graphics2D) gOld;
		g.setColor(Color.BLACK);
		g.setStroke(new BasicStroke(2f));
		Rectangle vis = getVisibleRect();
		Rectangle rect = new Rectangle((int) (vis.getX() + X_OFFSET),
				(int) (vis.getY() + vis.getHeight() - HEIGHT - Y_OFFSET),
				WIDTH, HEIGHT);
		g.fill(rect);

		paintMinimap(rect, g);

		g.setColor(Color.DARK_GRAY);
		g.draw(rect);

		paintViewport(getSize(), vis, rect, g);
	}

	private void paintMinimap(Rectangle rect, Graphics2D g)
	{
		for (Integer i : images.keySet())
		{
			if (images.get(i) != null)
			{
				Point origin = ((Main) getParent()).getOrigin();

				double scaleX = (double) WIDTH / (double) getSize().getWidth();
				double scaleY = (double) HEIGHT
						/ (double) getSize().getHeight();
				double xStart = (origin.getX() + images.get(i).getLeft())
						* scaleX;
				double yStart = (origin.getY() + images.get(i).getTop())
						* scaleY;
				g.drawImage(resizeImage(images.get(i), scaleX, scaleY),
						((int) (rect.getX() + xStart)),
						((int) (rect.getY() + yStart)), null);
			}
		}
	}

	private void paintViewport(Dimension size, Rectangle vis, Rectangle rect,
			Graphics2D g)
	{
		g.setColor(Color.DARK_GRAY);
		g.setStroke(new BasicStroke(2f));

		float xFactor = (float) WIDTH / (float) size.width;
		float yFactor = (float) HEIGHT / (float) size.height;

		Rectangle newRect = new Rectangle(
				(int) ((vis.getX() * xFactor) + rect.getX()),
				(int) ((vis.getY() * yFactor) + rect.getY()),
				(int) (vis.getWidth() * xFactor),
				(int) (vis.getHeight() * yFactor));

		g.draw(newRect);

	}

	private LayerImage resizeImage(LayerImage image, double scaleX,
			double scaleY)
	{
		LayerImage newImage = new LayerImage((int) (scaleX * image.getWidth()),
				(int) (scaleY * image.getHeight()));

		Graphics2D g = newImage.createGraphics();
		g.drawImage(image, 0, 0, (int) (scaleX * image.getWidth()),
				(int) (scaleY * image.getHeight()), null);
		return newImage;
	}

	private static int WIDTH = 200;
	private static int HEIGHT = 200;
	private static int X_OFFSET = 20;
	private static int Y_OFFSET = 20;
	private TreeMap<Integer, LayerImage> images;
}
